/**
 *  svhttpd         A Secure & Vitual http server
 *
 *  Copyright (c)   2007-2008 Dean To <svhttpd@gmail.com>
 *                  All Rights Reserved
 *  
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *  
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *  Filename        : misc.c
 *  Version         :
 *  Created         :
 *  Last Modified   :
 *
 *  HISTORY:
 *
 */

#include "misc.h"

char
hex2asc(int i)
{
    if (i < 0 || i > 15) 
        return ' ';
    if (i < 10)
        return ('0' + i);
    if (i >= 10)
        return ('A' + i - 10);
    return ' ';
}

int
is_ip_string(const char *ips)
{
    char *p, *q, buf[4];
    int tmpn, n; 
    
    n = 0;
    p = (char *)ips;
    while (p != NULL) {
        q = strchr(p, '.');
        if (q == NULL) {
            /* xxx */
            tmpn = strlen(p);
            if (tmpn == 0 || tmpn > 3)
                return 0; 
            strcpy(buf, p);
        } else {
            /* xxx. */
            if (q == p || q - p > 3)
                return 0; 
            strncpy(buf, p, q - p);
            buf[q - p] = '\0';
        }

        /* all is digit? */
        p = buf;
        while (*p != '\0') {
            if (!isdigit(*p))
                return 0;
            /* next */
            p++;
        }
        /* number should between [0,255] */
        tmpn = atoi(buf);
        if (tmpn < 0 || tmpn > 255)
            return 0;

        /* ok, get a number, then get next */
        n++;
        if (q == NULL) {
            break;
        } else {
            p = q + 1;
        }
    }

    /* is it 4 number in ips? */
    if (n != 4)
        return 0;

    return 1;
}

int
is_port_string(const char *ports)
{
    int port;
    const char *p;

    p = ports;
    while (*p != '\0') {
        if (!isdigit(*p))
            return 0;
        p++;
    }
    port = atoi(ports);
    if (port <= 0 || port > 0xffff)
        return 0;
    return port;
}
